package plugins.openform;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.FormShowParameter;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;

public class OpenNewsEditor extends AbstractBillPlugIn implements Plugin {

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);

        // 获取身份参数
        String identity = e.getFormShowParameter().getCustomParam("Identity");

        // 仅当身份为user时才查询历史记录
        if ("user".equals(identity)) {
            String currentUserName = RequestContext.get().getUserName();
            QFilter userFilter = new QFilter("dcb4_username", QCP.equals, currentUserName);

            DynamicObject record = BusinessDataServiceHelper.loadSingle(
                    "dcb4_news_editor",
                    "id",
                    new QFilter[]{userFilter}
            );

            if (record != null) {
                BillShowParameter parameter = (BillShowParameter) e.getFormShowParameter();
                parameter.setPkId(record.getPkValue());
                parameter.setStatus(OperationStatus.VIEW);
            }
        }
        // 非user身份直接保持默认新增状态
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);

        FormShowParameter param = this.getView().getFormShowParameter();
        String identity = param.getCustomParam("Identity");

        if ("user".equals(identity)) {
            this.getView().setVisible(false, "dcb4_invite");
        }
    }
}
